//
//  DDAddressAddInfoVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/8/1.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDAddressAddInfoVC.h"
#import "DDNetWorkAPIClient.h"
@interface DDAddressAddInfoVC ()

@property(nonatomic,strong)NSArray *datas;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)UIButton *checkBox;
@property(nonatomic,strong)NSMutableArray *textFields;
@end

@implementation DDAddressAddInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createUI
{
    __weak DDAddressAddInfoVC *weakSelf = self;
    self.view.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:self.title parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    [self AddLeftBtnAction:nil normal:@"top_返回" selected:@"top_返回" action:^{
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self AddRightBtnAction:@"确定" normal:nil selected:nil action:^{
        
        if (![weakSelf validateSubmit]) {
            return ;
        }
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        NSArray *keys = @[@"consignee",@"phoneNumber",@"postCode",@"district",@"address"];
        for (int i = 0; i < weakSelf.textFields.count; i++) {
            NSString * text = ((UITextField *) weakSelf.textFields[i]).text;
            text = text == nil ? @"" : text;
            [dict setValue:text forKey:keys[i]];
        }
        [dict setValue:_checkBox.selected ? @"1":@"0" forKey:@"def"];
        if (weakSelf.upadtes) {
             [dict setValue:_addressID forKey:@"id"];
            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
            [network updateAddress:dict completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                
                if (isSuccess) {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [weakSelf delayHUD:@"修改失败"];
                }
                
            }];
        }else{
            DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
            [network addAddress:dict completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
                
                if (isSuccess) {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [weakSelf delayHUD:@"保存失败"];
                }
                
            }];
        }
    }];
    
    
    
   // self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0.01)];
}

-(BOOL)validateSubmit
{
    BOOL result = YES;
    NSArray *messages = @[@"请输入收货人姓名",@"请输入11位手机号码",@"请输入6位编码",@"请输入所在地区",@"请输入详细地址"];
    for (int i = 0; i < self.textFields.count; i++) {
        NSString * text = ((UITextField *) self.textFields[i]).text;
        if (text.length == 0) {
            [self delayHUD:messages[i]];
            result = NO;
            break;
        }
//        if (i == 1 && ![self validateMobile:text]) {
        if (i == 1 && text.length != 11) {
            [self delayHUD:messages[i]];
            result = NO;
            break;
        }
        if (text.length != 6 && i == 2) {
            [self delayHUD:messages[i]];
            result = NO;
            break;
        }
    }
    
    return result;
}

- (void)createData
{
    _datas = @[@"收货人",@"手机号码",@"邮政编码",@"所在地区",@"详细地址",@"设置为默认地址"];
    _textFields = [NSMutableArray array];
}


#pragma mark -UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datas.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 70, 24)];
    
    nameLabel.text = _datas[indexPath.row];
    [cell.contentView addSubview:nameLabel];
    
    if (indexPath.row == 5) {
        nameLabel.frame = CGRectMake(10, 10, 130, 24);
        _checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
        _checkBox.frame = CGRectMake(self.tableView.frame.size.width-21, 14, 16, 16);
        [_checkBox setImage:[UIImage imageNamed:@"checkBox_off"] forState:UIControlStateNormal];
        [_checkBox setImage:[UIImage imageNamed:@"checkBox_on"] forState:UIControlStateSelected];
        if (_upadtes) {
            NSString *def = _upadtes[indexPath.row];
            _checkBox.selected = [def isEqualToString:@"1"]?YES : NO;
        }
        [cell.contentView addSubview:_checkBox];
    }else{
        UITextField *textFiled = [[UITextField alloc] initWithFrame:CGRectMake([self xPostiong:nameLabel sp:10], 0,self.tableView.frame.size.width-80, 44)];
        [_textFields addObject:textFiled];
        if (_upadtes) {
            textFiled.text = _upadtes[indexPath.row];
        }
        [cell.contentView addSubview:textFiled];
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 5) {
        _checkBox.selected = !_checkBox.selected;
    }
}


- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end
